package dwarffortress.loaders;

import java.io.Reader;
import java.io.IOException;

public abstract class RawLoader {
    protected void readRaw(Reader in) throws IOException {
        StringBuilder builder = null;
        int i = in.read();
        boolean inBracets = false;
        while (i >= 0) {
            char c = (char) i;
            if (c == '[') {
                if (inBracets) {
                    throw new IOException("Double opening bracets in raw file");
                }
                inBracets = true;
                builder = new StringBuilder();
            } else {
                if (c == ']') {
                    if (!inBracets) {
                        throw new IOException("Extra closing bracet in raw file");
                    }
                    inBracets = false;
                    handleElement(builder.toString());
                    builder = null;
                } else {
                    if (inBracets) {
                        builder.append(c);
                    }
                }
            }
            i = in.read();
        }
    }

    protected abstract void handleElement(String element) throws IOException;
}
